﻿using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace SwaggerDoc.Api
{
    /// <summary>
    /// ReDoc多语言
    /// </summary>
    public class XCodeSamplesOperationFilter : IOperationFilter
    {
        /// <summary>
        /// Apply
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="context"></param>
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            const string KEY = "x-code-samples";
            if (!operation.Extensions.ContainsKey(KEY))
            {
                var xCodeSamplesAttributes = context.MethodInfo
                                                    .GetCustomAttributes(true)
                                                    .OfType<XCodeSamplesAttribute>()  //自定义的Attribute
                                                    ;
                if (xCodeSamplesAttributes == null || !xCodeSamplesAttributes.Any())
                {
                    return;
                }

                OpenApiArray openApiArray = new OpenApiArray();
                foreach (var xCodeSamples in xCodeSamplesAttributes)
                {
                    openApiArray.Add(new OpenApiObject
                   {
                       {"lang", new OpenApiString(xCodeSamples.Lang)},
                       {"source", new OpenApiString(xCodeSamples.Source, true)}
                   });
                }
                operation.Extensions.Add(KEY, openApiArray);
            }
        }
    }

    /// <summary>
    /// 用来生成Swagger里面ReDoc多语言Sample例子。即："x-code-samples"里面的内容
    /// </summary>
    [System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple = true)]
    public class XCodeSamplesAttribute : Attribute
    {
        /// <summary>
        /// 语言
        /// </summary>
        public string Lang { get; set; }
        /// <summary>
        /// 代码
        /// </summary>
        public string Source { get; set; }
        /// <summary>
        /// XCodeSamplesAttribute
        /// </summary>
        /// <param name="lang"></param>
        /// <param name="source"></param>
        public XCodeSamplesAttribute(string lang, string source)
        {
            this.Lang = lang;
            this.Source = source;
        }
    }
}
